package com.example.netty.bio;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class BIOServer {
    public static void main(String[] args) throws IOException {
//        用serverSocket进行端口号设置和监听，真正的需要是用socket
        ServerSocket serverSocket = new ServerSocket(6666);
        ExecutorService threadPool = Executors.newCachedThreadPool();

        while (true) {
            final Socket socket = serverSocket.accept();
            System.out.println("成功连接");
            threadPool.execute(new Runnable() {
                @Override
                public void run() {
                    byte[] bytes = new byte[1024];
                    try (InputStream inputStream = socket.getInputStream()) {
                        //在服务器显示
                        while (true) {
                            int read = inputStream.read(bytes);
                            if (read != -1) {
                                System.out.println(new String(bytes,0,read));
                                //回应客户端
                                OutputStream outputStream = socket.getOutputStream();
                                outputStream.write("收到！".getBytes());
                            }else {
                                break;
                            }
                        }
                    } catch (IOException e) {
                        throw new RuntimeException(e);
                    };
                }
            });
        }
    }



}
